<?php
class Application_Service_Auction
{
	private static $_instance = NULL;
	
    private function __construct () {}
    
    private function __clone() {}
    
    public static function getInstance() {
    	if(self::$_instance == NULL) {
    		self::$_instance = new self();
    	}
    	return self::$_instance;
    }
    
    // 读取已激活拍动
    public function getActiveAuction() {
    	
    	$modelAuction = new Application_Model_Auction();
    	
    	// get all acitve auctions
    	$status = Application_Model_Constants::$AUCTION_STATUS_ACTIVE;
    	$auctions = $modelAuction->getAuctionByStatus($status);

    	$result = array();
    	
    	foreach ($auctions as $auction) {
    		
    		$auction = $this->convertAuction($auction);
    		array_push($result, $auction);
    	}
    	
    	return $result;
    }
    
    // 获得指定ID商品及已激活拍卖
    public function getActiveAuctionOrId($id) {
    	
    	$modelAuction = new Application_Model_Auction();
    	
    	// 获得竞拍商品
    	$status = Application_Model_Constants::$AUCTION_STATUS_ACTIVE;
    	$auctions = $modelAuction->getAuctionOrId($id, $status);
    	
    	// 对结果进行排序，ID对应的商品第一个，其他按竞拍优先级
    	$result = array();
    	$temp = array();
    	
    	foreach ($auctions as $auction) {
    		
    		$auction = $this->convertAuction($auction);
    		
    		if($auction['id'] != $id) {
    			array_push($temp, $auction);
    		} else {
    			array_push($result, $auction);
    		}
    	}
    	
    	$result = array_merge($result, $temp);
    	    	
    	return $result;
    	
    }
    
    public function bid($auction_id) {
    	
    	$modelUser = new Application_Model_User();
    	$modelAuction = new Application_Model_Auction();
    	
    	// 验证用户是否为激活状态
    	
    	// 验证用户账户余额
    	
    	// 
    }
    
    private function convertAuction($auction) {
    	
    		$brand = $auction->findParentRow("Application_Model_Brand");
    		$user = $auction->findParentRow("Application_Model_User");
    		$category = $auction->findParentRow("Application_Model_Category");
    	
    		$auction = $auction->toArray();
    		
    		// 格式化金额
    		$auction['current_price'] = number_format($auction['current_price'], 2, '.', ',');
    		$auction['retail_price'] = number_format($auction['retail_price'], 2, '.', ',');
    		
    		// 格式化剩余时间

			
    		// 获得品牌，类型，最后出价人
			$auction['brand_name_cn'] = $brand->name_cn;
			$auction['brand_name_en'] = $brand->name_en;
			$auction['brand_since'] = $brand->since;
			$auction['brand_country'] = $brand->country;
			$auction['brand_info'] = $brand->info;
			$auction['brand_logo'] = $brand->logo;
			$auction['category_name'] = $category->name;
			$auction['user_name'] = $user->name;
			$auction['user_home_page'] = $user->home_page;
			$auction['user_head'] = $user->head;
			
			return $auction;	
    }
    
}
?>